package com.hopu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hopu.exception.BusinessException;
import com.hopu.exception.NoLoginException;
import com.hopu.mapper.StaffMapper;
import com.hopu.pojo.Organization;
import com.hopu.pojo.PageData;
import com.hopu.pojo.Staff;
import com.hopu.service.OrganizationService;
import com.hopu.service.StaffService;
import com.hopu.utils.JwtUtils;
import com.hopu.vo.StaffVo;
import io.netty.util.internal.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author YwaiX
 * @since 2024-09-12
 */
@Service
public class StaffServiceImpl extends ServiceImpl<StaffMapper, Staff> implements StaffService {

    @Autowired
    private StaffMapper staffMapper;

    @Autowired
    private OrganizationService organizationService;

    /**
     * 获取员工列表-袁胡宇
     *
     * @param page
     * @return
     */
    @Override
    public PageData<StaffVo> selectAll(Page<Staff> page, Staff staffInfo) {
        QueryWrapper<Staff> queryWrapper = new QueryWrapper<>();

        if (staffInfo.getStaffNo() != null && !staffInfo.getStaffNo().isEmpty()) {
            queryWrapper.eq("staff_no", staffInfo.getStaffNo());
        }
        if (staffInfo.getRealName() != null && !staffInfo.getRealName().isEmpty()) {
            queryWrapper.like("real_name", staffInfo.getRealName());
        }
        if (staffInfo.getOrganizationId() != null) {
            queryWrapper.eq("organization_id", staffInfo.getOrganizationId());
        }

        //分页获取所有的staff对象
        staffMapper.selectPage(page, queryWrapper);
        //将获取的对象存放到集合
        List<Staff> list = page.getRecords();
        //创建一个集合
        List<StaffVo> staffVos = new ArrayList<>();
        //通过循环查询对象的组织名称
        for (int i = 0; i < list.size(); i++) {
            //获取单个对象
            Staff staff = list.get(i);
            //获取对象所属的组织
            Organization organization = organizationService.getOrganizationById(staff.getOrganizationId());
            //将staff对象个所属的组织名称装到StaffVo中
            StaffVo staffVo = new StaffVo(staff, organization.getOrganizationName());
            //将vo添加到集合
            staffVos.add(staffVo);
        }
        //封装PageData
        PageData<StaffVo> pageData = new PageData<>((int) page.getPages(), (int) page.getSize(), (int) page.getTotal(), staffVos);
        return pageData;
    }

    @Override
    public String login(Staff staff) {
        Staff selectOne = staffMapper.selectOne(new LambdaQueryWrapper<Staff>().eq(Staff::getStaffNo, staff.getStaffNo()));
        System.out.println("selectOne"+selectOne);
        if (selectOne == null) {
            throw new NoLoginException("工号ID错误！");
        }
        if (!selectOne.getPassword().equals(staff.getPassword())) {
            throw new NoLoginException("用户密码错误！");
        }
        return JwtUtils.createToken(String.valueOf(selectOne.getId()));
    }

    /**
     * 修改员工
     *
     * @param staff
     */
    @Override
    public void update(Staff staff) {
        LambdaQueryWrapper<Staff> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Staff::getIdCard, staff.getIdCard());
        Staff staff2 = getOne(lambdaQueryWrapper);
        if (staff2 != null && !staff2.getStaffNo().equals(staff.getStaffNo())) {
            throw new BusinessException("身份证号不能重复");
        }
        LambdaUpdateWrapper<Staff> updateWrapper = new LambdaUpdateWrapper<>();
        if (StringUtil.isNullOrEmpty(staff.getStaffNo())){
            throw new BusinessException("用户编号不能为空");
        }
        updateWrapper.eq(Staff::getStaffNo, staff.getStaffNo());

        // 使用 Lambda 表达式动态更新字段
        Optional.ofNullable(staff.getRealName()).ifPresent(name -> updateWrapper.set(Staff::getRealName, name));
        Optional.ofNullable(staff.getPassword()).ifPresent(password -> updateWrapper.set(Staff::getPassword, password));
        Optional.ofNullable(staff.getGender()).ifPresent(gender -> updateWrapper.set(Staff::getGender, gender));
        Optional.ofNullable(staff.getIdCard()).ifPresent(idCard -> updateWrapper.set(Staff::getIdCard, idCard));
        Optional.ofNullable(staff.getDateOfBirth()).ifPresent(dob -> updateWrapper.set(Staff::getDateOfBirth, dob));
        Optional.ofNullable(staff.getPhone()).ifPresent(phone -> updateWrapper.set(Staff::getPhone, phone));
        Optional.ofNullable(staff.getOrganizationId()).ifPresent(orgId -> updateWrapper.set(Staff::getOrganizationId, orgId));
        Optional.ofNullable(staff.getJobName()).ifPresent(jobName -> updateWrapper.set(Staff::getJobName, jobName));
        Optional.ofNullable(staff.getStatus()).ifPresent(status -> updateWrapper.set(Staff::getStatus, status));
        /*Optional.ofNullable(staff.getUpdateBy()).ifPresent(updateBy -> updateWrapper.set(Staff::getUpdateBy, updateBy));
        Optional.ofNullable(staff.getUpdateTime()).ifPresent(updateTime -> updateWrapper.set(Staff::getUpdateTime, updateTime));

        Optional.ofNullable(staff.getIsFirstLogin()).ifPresent(firstLogin -> updateWrapper.set(Staff::getIsFirstLogin, firstLogin));
*/
        update(updateWrapper);
    }

    /**
     * 根据员工编号查询员工信息
     *
     * @param staffNo
     * @return
     */
    @Override
    public StaffVo staffInfo(String staffNo) {
        System.out.println(staffNo);
        //查询个人
        Staff staff = staffMapper.selectOne(new LambdaQueryWrapper<Staff>().eq(Staff::getStaffNo, staffNo));
        //查询组织a
        Organization organization = organizationService.getOrganizationById(staff.getOrganizationId());
        return new StaffVo(staff, organization.getOrganizationName());
    }

    /**
     * 添加员工
     *
     * @param staff
     */
    @Override
    public void add(Staff staff) {
        LambdaQueryWrapper<Staff> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Staff::getIdCard, staff.getIdCard());
        Staff staff2 = getOne(lambdaQueryWrapper);
        if (staff2 != null) {
            throw new BusinessException("员工已存在");
        }
        //插入用户
        save(staff);
    }

    @Override
    public void updateInfo(String staffNo, String password, String phone,String realName,String gender,String photoUrl) {
        staffMapper.updateInfo(staffNo, password, phone, realName, gender, photoUrl);
    }


    /**
     * 修改员工状态
     *
     * @param id
     * @param status
     */
    @Override
    public void updateStatus(Integer id, Integer status) {
        baseMapper.updateById(new Staff().setId(id).setStatus(status));
    }

    /**
     * 批量删除用户
     *
     * @param ids
     */
    @Override
    public void deleteStaff(List<Integer> ids) {
        baseMapper.deleteByIds(ids);
    }
}

